﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Bom.Dto;
using Camc.Quality.Bop;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.Dto;
using Camc.Quality.Dto.TableDto.BopDto.Substance;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials.Dto;
using Camc.Quality.Materials.MaterialsInterface;
using Camc.Quality.Materials.TreeObject;
using Camc.Quality.OperationHistory;
using Camc.Quality.StoreManagement.SoreModel.Dto;
using EFCore.BulkExtensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; 

namespace Camc.Quality.Materials
{
    public class MaterialsAppService : QualityAppServiceBase
    {
        List<TreeClassDto> treeClassDtos = new List<TreeClassDto>();
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IRepository<MaterialsDesc, Guid> _materiaDesclsRepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IMaterialsExportToExcel _materialsExportListExcelExporter;
        private readonly IAbpSession _abpSession;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IMaterialsImportToTable _materialsImportToTable = new MaterialsImportToTable();
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        public MaterialsAppService(IUnitOfWorkManager unitOfWorkManager,
        IAbpSession abpSession, IRepository<MaterialsNode, Guid> materialsNodeRepository, IRepository<MaterialsDesc, Guid> materiaDesclsRepository, IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<User, long> userRepository, IRepository<Sys_Code, Guid> sysCodeRepository, IMaterialsExportToExcel materialsExportListExcelExporter, IRepository<BomDesign, Guid> bomDesignrepository, IOperationHistoryAppService iOperationHistoryAppService, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository
           )
        {
            _materialsNodeRepository = materialsNodeRepository;
            _materiaDesclsRepository = materiaDesclsRepository;
            _materialsContentRepository = materialsContentRepository;
            _materialsExportListExcelExporter = materialsExportListExcelExporter;
            _abpSession = abpSession;
            _userRepository = userRepository;
            _sysCodeRepository = sysCodeRepository;
            _unitOfWorkManager = unitOfWorkManager;
            _bomDesignrepository = bomDesignrepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _bomDesignDetailrepository = bomDesignDetailrepository;

            //  _contextAccessor = contextAccessor;
        }
    /// <summary>
    /// 获取物料建模树主节点
    /// </summary>
    /// <param name="materialsDescDto"></param>
    /// <returns></returns>
    public List<MaterialsDescDto> GetDescTreeGrid()
        {
            var materialsDesc = _materiaDesclsRepository.GetAll().ToList();
            if (materialsDesc != null)
            {
                return ObjectMapper.Map<List<MaterialsDescDto>>(materialsDesc).ToList();
            }
            return new List<MaterialsDescDto>();
        }
        /// <summary>
        /// 物料建模树加载
        /// </summary>
        /// <returns></returns>
        public List<TreeClassDto> GetTreeGrid(Guid ParentId)
        {

            List<MaterialsNode> materialsNodes = null;
            materialsNodes = _materialsNodeRepository.GetAll().Where(t => t.ParentCode == ParentId).OrderBy(t=>t.CreationTime).ToList();
            if (materialsNodes != null)
            {
                if (materialsNodes != null && materialsNodes.Count > 0)
                {
                    foreach (var item in materialsNodes)
                    {
                        TreeClassDto treeClassDto = new TreeClassDto
                        {
                            Id = item.Id,
                            HasChild = item.HasChild,
                            MaterialTypeName = item.MaterialTypeName,
                            OrderNum = item.OrderNum,
                            ParentCode = item.ParentCode,
                            LevelNum = item.LevelNum,
                            MaterialTypeCode = item.MaterialsTypeCode
                        };
                        treeClassDtos.Add(treeClassDto);
                    }
                }
                return treeClassDtos;
            }
            return treeClassDtos;
        }

        /// <summary>
        /// 删除物料建模树节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteNode(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var materialasChildNode = _materialsNodeRepository.FirstOrDefaultAsync(b => b.Id == id).Result;
                if (materialasChildNode != null)
                {
                    int childNodeCount = await _materialsNodeRepository.CountAsync(t => t.ParentCode == id);
                    if (childNodeCount == 0)
                    {
                        //判断附表有没有对应数据
                        int materiaContentCount = await _materialsContentRepository.CountAsync(t => t.MaterialsNodeId == materialasChildNode.Id || t.MaterialCategoryId == id);
                        if (materiaContentCount > 0)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "该节点下存在有效数据,请先删除";
                            return resultMessage;
                            //throw new UserFriendlyException("该节点下存在有效数据,请先删除");
                        }
                        else
                        {
                            await _materialsNodeRepository.DeleteAsync(t => t.Id == id && t.MaterialTypeName.StartsWith(materialasChildNode.MaterialTypeName));
                        }
                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "该节点下存在子节点,请先删除子节点";
                        return resultMessage;
                        //throw new UserFriendlyException("该节点下存在子节点,请先删除子节点");

                    }
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该节点异常,请重试或联系管理员";
                    return resultMessage;
                    //throw new UserFriendlyException("该节点异常,请重试或联系管理员");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 物料建模节点新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StoreReturnIdDto> CreateOrUpdateMaterialsNode(MaterialsNodeEditDto materialsNodeEditDto)
        {
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            if (materialsNodeEditDto.Id == Guid.Empty)
            {
                storeReturnIdDto = await CreateMaterialsNode(materialsNodeEditDto);
                _unitOfWorkManager.Current.SaveChanges();
            }
            else
            {
                await UpdateMaterialsNode(materialsNodeEditDto);
            }
            return storeReturnIdDto;
        }
        /// <summary>
        /// 物料建模详细信息新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StoreReturnIdDto> CreateOrUpdateMaterialsContent(MaterialsEditContentDto materialsEditContentDto)
        {
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            if (materialsEditContentDto.Id == Guid.Empty)
            {
                storeReturnIdDto = await CreateMaterialsContent(materialsEditContentDto);
            }
            else
            {
                storeReturnIdDto = await UpdateMaterialsContent(materialsEditContentDto);
            }
            return storeReturnIdDto;
        }

        /// <summary>
        /// 物料建模详细信息新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StoreReturnIdDto> CreateOrUpdateErnalMaterialsContent(MaterialsEditContentDto materialsEditContentDto)
        {
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            if (materialsEditContentDto.Id == Guid.Empty)
            {
                storeReturnIdDto = await CreateErnalMaterialsContent(materialsEditContentDto);
            }
            else
            {
                //storeReturnIdDto = await UpdateErnalMaterialsContent(materialsEditContentDto);
            }
            return storeReturnIdDto;
        }

        /// <summary>
        /// 增加节点
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<StoreReturnIdDto> CreateMaterialsNode(MaterialsNodeEditDto materialsNodeEditDto)
        {

            StoreReturnIdDto storeReturnId = new StoreReturnIdDto();
            if (materialsNodeEditDto.MaterialTypeName.Trim() == "")
            {
                throw new UserFriendlyException("类别名称不能为空");
            }
            var typeNameCount = _materialsNodeRepository.Count(t => t.MaterialTypeName == materialsNodeEditDto.MaterialTypeName.Trim());
            if (typeNameCount != 0) 
            {
                storeReturnId.code = 1;
                storeReturnId.Message = "已存在";
                return storeReturnId;
            }
            int queryMaterialDesc = _materiaDesclsRepository.Count(t => t.Id == Guid.Parse("fa568b8c-4eb5-47b1-92b1-f5aaff234de4"));
            if (queryMaterialDesc == 0)
            {
                MaterialsDesc materialsDesc = new MaterialsDesc
                {
                    Id = Guid.Parse("fa568b8c-4eb5-47b1-92b1-f5aaff234de4"),
                    Materialname = "物料",
                };
                await _materiaDesclsRepository.InsertAsync(materialsDesc);
             //   _unitOfWorkManager.Current.SaveChanges();
            }
            //添加默认发次和组件类型
            int queryMaterialTop = _materialsNodeRepository.Count(t => t.Id == Guid.Parse("a32a2fae-3938-4937-8906-0e831debbe93") && t.ParentCode == Guid.Empty);
            if (queryMaterialTop == 0)
            {
                MaterialsNode materialsNodeEdit = new MaterialsNode
                {
                    Id = Guid.Parse("a32a2fae-3938-4937-8906-0e831debbe93"),
                    MaterialTypeName = "",
                    HasChild = false,
                    LevelNum = 0,
                    MaterialsDescId = Guid.Parse("fa568b8c-4eb5-47b1-92b1-f5aaff234de4")
                };
                await _materialsNodeRepository.InsertAsync(materialsNodeEdit);
                _unitOfWorkManager.Current.SaveChanges();
            }
            //查找是否有父级数据
            var materiaParentNode = _materialsNodeRepository.GetAll().Where(t => t.Id == materialsNodeEditDto.ParentCode);
            if (materiaParentNode.Count() > 0)
            { // 根据parentCode 找到 父级 根据id 更新父级的HasChild 
                var materiaParentNodeResult = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsNodeEditDto.ParentCode).Result;
                if (materiaParentNodeResult.Id != Guid.Empty)
                {
                    materiaParentNodeResult.HasChild = true;
                    await _materialsNodeRepository.UpdateAsync(materiaParentNodeResult);
                }
                //找出当前父节点下有几条数据 如果大于0 说明有子级 新增时 总条数加一
                int materialNodeCount = _materialsNodeRepository.Count(t => t.ParentCode == materialsNodeEditDto.ParentCode);
                //if (materialNodeCount == 0)
                //{
                //    materialsNodeEditDto.MaterialTypeCode = materialsNodeEditDto.MaterialTypeCode + '_' + (materialNodeCount);
                //}
                //else
                //{
                materialsNodeEditDto.MaterialTypeCode = materialsNodeEditDto.MaterialTypeCode + '_' + (materialNodeCount + 1);
                // }
            }

            //var materiaChildNode = _materialsNodeRepository.GetAll().Where(t => t.ParentCode.Equals(materiaParentNode.Id)).ToList();
            ////降序取最大序号
            //materiaChildNode = materiaChildNode.OrderByDescending(o => o.LevelNum).ToList();
            // int levelNum = materiaChildNode[0].LevelNum;
            MaterialsNode materialsNode = new MaterialsNode()
            {
                MaterialsDescId = materialsNodeEditDto.MaterialsDescId,
                MaterialTypeName = materialsNodeEditDto.MaterialTypeName,
                ParentCode = materialsNodeEditDto.ParentCode,
                HasChild = materialsNodeEditDto.HasChild,
                LevelNum = materialsNodeEditDto.LevelNum + 1,
                MaterialsTypeCode = materialsNodeEditDto.MaterialTypeCode,
                Id = Guid.NewGuid()
            };
            //如果没有父级 那就已当前id作为code
            if (materiaParentNode.Count() == 0)
            {
                if (string.IsNullOrEmpty(materialsNodeEditDto.MaterialTypeCode))
                {
                    materialsNodeEditDto.MaterialTypeCode = "";
                }
                materialsNode.MaterialsTypeCode = materialsNode.Id.ToString();
            }
            var guid = await _materialsNodeRepository.InsertAndGetIdAsync(materialsNode);
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto()
            {
                MaterialCategoryId = guid,
                MaterialTypeCode = materialsNodeEditDto.MaterialTypeCode,
            };

            return storeReturnIdDto;
        }
        /// <summary>
        /// 更新节点
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateMaterialsNode(MaterialsNodeEditDto materialsNodeEditDto)
        {
            if (materialsNodeEditDto.MaterialTypeName.Trim() == "")
            {
                throw new UserFriendlyException("类别名称不能为空");
            }
            var materialsNodeCount = await _materiaDesclsRepository.CountAsync(t => t.Id == materialsNodeEditDto.Id);
            if (materialsNodeCount > 0)
            {
                var materialsNodeDataParent = await _materiaDesclsRepository.FirstOrDefaultAsync(t => t.Id == materialsNodeEditDto.Id);
                if (materialsNodeDataParent != null)
                {
                    materialsNodeDataParent.Materialname = materialsNodeEditDto.MaterialTypeName;
                }
                await _materiaDesclsRepository.UpdateAsync(materialsNodeDataParent);
            }
            else
            {
                var materialsNodeData = await _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsNodeEditDto.Id);
                if (materialsNodeData != null)
                {
                    materialsNodeData.MaterialTypeName = materialsNodeEditDto.MaterialTypeName;
                }
                await _materialsNodeRepository.UpdateAsync(materialsNodeData);
            }
      
            
        }
        /// <summary>
        /// 根据节点获取物料详细信息
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<MaterialsContentDto>> GetmaterialsContentByNode(GetMaterialsContentListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            var query = from materialsContent in _materialsContentRepository.GetAll()
                       // .WhereIf(!input.MaterialTypeId.Equals(Guid.Empty),t=>t.MaterialsNodeId ==input.MaterialTypeId)
                        .WhereIf(!input.MaterialTypeCode.IsNullOrWhiteSpace(), t => t.MaterialTypeCode.StartsWith(input.MaterialTypeCode))
                        .WhereIf(!input.MaterialName.IsNullOrWhiteSpace(), t => t.MaterialName.Contains(input.MaterialName)).WhereIf(!input.Model.IsNullOrWhiteSpace(), t => t.Model.Contains(input.Model)).WhereIf(!input.MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo.Contains(input.MaterialNo))
                            //.WhereIf(!input.MaterialTypeId.Equals(Guid.Empty) && !input.MaterialCategoryId.Equals(Guid.Empty), x => x.MaterialCategoryId.Equals(input.MaterialTypeId))
                        join materialsNode in _materialsNodeRepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.Contains(input.MaterialTypeName)) on materialsContent.MaterialsNodeId equals materialsNode.Id
                        join materialsNodeTwo in _materialsNodeRepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeTwo.Id
                        into materialsSegmentation
                        from ms in materialsSegmentation.DefaultIfEmpty()
                        join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                        into codeData
                        from cd in codeData.DefaultIfEmpty()
                        join users in userData on materialsContent.CreatorUserId equals users.Id
                        join code2 in _sysCodeRepository.GetAll() on materialsContent.ModelId equals code2.Id
                        into codeData2
                        from cd2 in codeData2.DefaultIfEmpty()
                        join code3 in _sysCodeRepository.GetAll() on materialsContent.SendTimeId equals code3.Id
                        into codeData3
                        from cd3 in codeData3.DefaultIfEmpty()
                        select new MaterialsContentDto
                        {
                            MaterialName = materialsContent.MaterialName,
                            MaterialNo = materialsContent.MaterialNo,
                            Model = materialsContent.Model,
                            MaterialTypeName = materialsNode.MaterialTypeName,
                            Id = materialsContent.Id,
                            UnitId = cd == null ? Guid.Empty : cd.Id,
                            Unit = cd == null ? "" : cd.Description,
                            IsUsed = Enum.Parse(typeof(MaterialsEnum.UsedIs), materialsContent.IsUsed.ToString()).ToString(),
                            IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                            IsStandard = Enum.Parse(typeof(MaterialsEnum.IsStandard), materialsContent.IsStandard.ToString()).ToString(),
                            Remark = materialsContent.Remark,
                            MaterialTypeId = materialsContent.MaterialsNodeId,
                            MaterialCategoryId = materialsContent.MaterialCategoryId,
                            MaterialProperty = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialsContent.MaterialProperty.ToString()).ToString(),
                            MaterialPropertyId = materialsContent.MaterialProperty,
                            CreateUser = users.Surname + users.Name,
                            MaterialCategoryName = ms.MaterialTypeName,
                            Batch = materialsContent.Batch,
                            ParentCode = materialsNode.ParentCode,
                            CreationTime = materialsContent.CreationTime,
                            MaterialsTypeCode = materialsContent.MaterialTypeCode
                        };
            if (query != null && query.Count() > 0)
            {
                try
                {
                    var materialsContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    return new PagedResultDto<MaterialsContentDto>(query.Count(), materialsContentDataList);
                }
                catch (Exception ex)
                {
                }
            }
            return new PagedResultDto<MaterialsContentDto>();
        }
        /// <summary>
        /// 根据过滤条件获取物料信息
        /// </summary> 
        /// <param name="typeId"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<MaterialsContentDto>> GetmaterialsContentByFilter(GetMaterialsContentListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            var query = from materialsContent in _materialsContentRepository.GetAll().WhereIf(!input.MaterialTypeId.Equals(Guid.Empty) || !input.MaterialName.IsNullOrWhiteSpace() || !input.Model.IsNullOrWhiteSpace(),
                x => x.MaterialsNodeId.Equals(input.MaterialTypeId) ||
                x.MaterialName.Contains(input.MaterialName) ||
                x.Model.Contains(input.Model)
                ).WhereIf(!input.MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo.Contains(input.MaterialNo))
                        join materialsNode in _materialsNodeRepository.GetAll() on materialsContent.MaterialsNodeId equals materialsNode.Id
                        join materialsNodeTwo in _materialsNodeRepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeTwo.Id
                        into materialsSegmentation
                        from ms in materialsSegmentation.DefaultIfEmpty()
                        join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                        into codeData
                        from cd in codeData.DefaultIfEmpty()
                        join users in userData on materialsContent.CreatorUserId equals users.Id
                        select new MaterialsContentDto
                        {
                            Id = materialsContent.Id,
                            MaterialName = materialsContent.MaterialName,
                            MaterialNo = materialsContent.MaterialNo,
                            Model = materialsContent.Model,
                            MaterialTypeName = materialsNode.MaterialTypeName,
                            UnitId = cd.Id,
                            Unit = cd.Code,
                            IsUsed = Enum.Parse(typeof(MaterialsEnum.UsedIs), materialsContent.IsUsed.ToString()).ToString(),
                            IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                            IsStandard = Enum.Parse(typeof(MaterialsEnum.IsStandard), materialsContent.IsStandard.ToString()).ToString(),
                            Remark = materialsContent.Remark,
                            MaterialTypeId = materialsContent.MaterialsNodeId,
                            MaterialProperty = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialsContent.MaterialProperty.ToString()).ToString(),
                            MaterialPropertyId = materialsContent.MaterialProperty,
                            CreateUser = users.Surname + users.Name,
                            MaterialCategoryName = ms.MaterialTypeName
                        };
            if (query != null)
            {
                try
                {
                    var materialsContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    return new PagedResultDto<MaterialsContentDto>(query.Count(), materialsContentDataList);
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            else
            {
                throw new UserFriendlyException("异常,请重试或联系管理员");
            }
        }
        /// <summary>
        /// 增加物料详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<StoreReturnIdDto> CreateMaterialsContent(MaterialsEditContentDto materialsEditContentDto)
        {

            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            try
            {
                int queryCount = 0;
                Guid nodeTypeId = Guid.Empty;
                var model = materialsEditContentDto.Model == null || materialsEditContentDto.Model == "" ? "-" : materialsEditContentDto.Model.Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                materialsEditContentDto.MaterialNo = materialsEditContentDto.MaterialNo.ToUpper();
                queryCount = _materialsContentRepository.Count(t => t.MaterialNo == materialsEditContentDto.MaterialNo && t.Model == model);
                if (queryCount > 0)
                {
                    storeReturnIdDto.code = 1;
                    storeReturnIdDto.Message = "物料建模中已存在相同图号规格！无需重复添加";
                    return storeReturnIdDto;
                    //throw new UserFriendlyException("该物料已存在！");
                }
                if (materialsEditContentDto.ModelId != Guid.Empty && materialsEditContentDto.SendTimeId != Guid.Empty)
                {
                    queryCount = _materialsContentRepository.Count(t => t.ModelId == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId);
                    if (queryCount == 0)
                    {
                        if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.整装)
                        {
                            var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.整装.ToString()).Result;
                            if (materialsNode != null)
                            {
                                nodeTypeId = materialsNode.Id;
                            }
                        }
                    }
                }
                else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                {

                    if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.芯级.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                        }
                    }
                    else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.部件.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                            model = "-";
                        }
                    }
                    else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.组件.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                        }
                    }
                }
                //else
                //{
                //    queryCount = _materialsContentRepository.Count(t => t.MaterialNo == materialsEditContentDto.MaterialNo && t.Model == materialsEditContentDto.Model);
                //}

                //if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.整装 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                //{
                //    materialsEditContentDto.MaterialsNodeId = Guid.Parse("a32a2fae-3938-4937-8906-0e831debbe93");
                //}
                //string typeCode = "";
                //if (materialsEditContentDto.MaterialCategoryId != Guid.Empty) 
                //{
                //    var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId).Result;
                //    typeCode = materialsNode.MaterialsTypeCode+"_"+1;
                //}
                
                if (materialsEditContentDto.MaterialCategoryId!=Guid.Empty&& materialsEditContentDto.MaterialsNodeId!=Guid.Empty&&materialsEditContentDto.MaterialTypeCode ==null) 
                {
                    Guid parenCode = Guid.Empty;
                    if (materialsEditContentDto.MaterialCategoryId == materialsEditContentDto.MaterialsNodeId)
                    {
                        var queryMaterialsDesc = _materiaDesclsRepository.GetAll().FirstOrDefaultAsync().Result;
                        if (queryMaterialsDesc != null)
                        {
                            parenCode = queryMaterialsDesc.Id;
                        }
                        var queryMaterialsNodeContent = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId && t.ParentCode == parenCode).Result;
                        if (queryMaterialsNodeContent != null)
                        {
                            materialsEditContentDto.MaterialTypeCode = queryMaterialsNodeContent.MaterialsTypeCode;
                        }
                    }
                    else 
                    {
                    
                        var queryMaterialsNodeContent = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId && t.ParentCode == materialsEditContentDto.MaterialsNodeId).Result;
                        if (queryMaterialsNodeContent != null)
                        {
                            materialsEditContentDto.MaterialTypeCode = queryMaterialsNodeContent.MaterialsTypeCode;
                        }
                    }
                    
                }
                
                MaterialsContent materialsContent = new MaterialsContent()
                {
                    //物料代码
                    MaterialNo = materialsEditContentDto.MaterialNo,
                    //物料名称
                    MaterialName = materialsEditContentDto.MaterialName,
                    //规格型号
                    Model = model,
                    //类型id
                    MaterialsNodeId = nodeTypeId == Guid.Empty ? materialsEditContentDto.MaterialsNodeId: nodeTypeId,
                    //单位
                    UnitId = materialsEditContentDto.UnitId,
                    //是否使用
                    IsUsed = materialsEditContentDto.IsUsed,
                    //是否关键件
                    IsKeyPart = materialsEditContentDto.IsKeyPart, 
                    //是否标准件
                    IsStandard = materialsEditContentDto.IsStandard,
                    //备注
                    Remark = materialsEditContentDto.Remark,
                    //图号
                    DrawingNo = materialsEditContentDto.DrawingNo,
                    //发次
                    // SendTime = materialsEditContentDto.SendTime,
                    //物料类别组合编码
                    MaterialTypeCode = nodeTypeId == Guid.Empty ? materialsEditContentDto.MaterialTypeCode : nodeTypeId + "_1",
                    //物料属性
                    MaterialProperty = materialsEditContentDto.MaterialProperty,
                    //物料细分类别
                    MaterialCategoryId = materialsEditContentDto.MaterialCategoryId,
                    //批次
                    Batch = materialsEditContentDto.Batch,
                    SendTime = materialsEditContentDto.SendTime,
                    ModelId = materialsEditContentDto.ModelId,
                    SendTimeId = materialsEditContentDto.SendTimeId
                };
                //add start 11/30
                //if (materialsContent.MaterialTypeCode == null)
                //{
                //    var materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialsNodeId);
                //    if (materialsContent.MaterialCategoryId == Guid.Empty)
                //    {
                //        if (materialsNode != null)
                //        {
                //            materialsContent.MaterialTypeCode = materialsContent.MaterialTypeCode + "_1";
                //        }
                //        else 
                //        {
                //            materialsContent.MaterialTypeCode = "fa568b8c-4eb5-47b1-92b1-f5aaff234de4_1";
                //        }
                //    }
                //    else
                //    {
                //        materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialCategoryId);
                //        if (materialsNode != null)
                //        {
                //            materialsContent.MaterialTypeCode = materialsContent.MaterialTypeCode + "_1";
                //        }
                //        else
                //        {
                //            materialsContent.MaterialTypeCode = "fa568b8c-4eb5-47b1-92b1-f5aaff234de4_1";
                //        }
                //    }
                //};
                //end 11/30
                var guid = await _materialsContentRepository.InsertAndGetIdAsync(materialsContent);
                _unitOfWorkManager.Current.SaveChanges();
                //_unitOfWorkManager.Current.SaveChanges();
                //var query = (from materialsContentQuery in _materialsContentRepository.GetAll().Where(t => t.MaterialProperty == 0&&t.Id ==guid)
                //            join matgerialsNode in _materialsNodeRepository.GetAll()
                //            on materialsContent.MaterialsNodeId equals matgerialsNode.Id
                //            into Joinnc
                //            from bm in Joinnc.DefaultIfEmpty()
                //            join materialsNode2 in _materialsNodeRepository.GetAll()
                //            on materialsContent.MaterialCategoryId equals materialsNode2.Id
                //            into Joinmn
                //            from mn in Joinmn.DefaultIfEmpty()
                //            join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                //               into codeData
                //            from cd in codeData.DefaultIfEmpty()
                //            join code2 in _sysCodeRepository.GetAll() on materialsContent.ModelId equals code2.Id
                //                        into codeData2
                //            from cd2 in codeData2.DefaultIfEmpty()
                //            join code3 in _sysCodeRepository.GetAll() on materialsContent.SendTimeId equals code3.Id
                //            into codeData3
                //            from cd3 in codeData3.DefaultIfEmpty()
                //            where (materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.整装) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.部件) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.组件))
                //            select new BomMainSelectParentContentListDto
                //            {
                //                Id = materialsContent.Id,
                //                MaterialTypeId = materialsContent.MaterialsNodeId,
                //                MaterialNo = materialsContent.MaterialNo,
                //                MaterialName = materialsContent.MaterialName,
                //                Model = cd2.Description,
                //                MaterialTypeName = bm.MaterialTypeName,
                //                MaterialSegmentationName = mn.MaterialTypeName,
                //                IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                //                DrawingNo = materialsContent.DrawingNo,
                //                // Unit1BomDosage = bd.Unit1BomDosage,
                //                UnitId = materialsContent.UnitId,
                //                UnitName = cd.Description,
                //                Remark = materialsContent.Remark,
                //                Attribute = materialsContent.MaterialProperty,
                //                SendTime = cd3.Description,
                //                ModelId = materialsContent.ModelId,
                //                SendTimeId = materialsContent.SendTimeId
                //            }).FirstOrDefault();

                var fccount = _bomDesignrepository.Count(t => t.ModuleId == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId);
       
                if (fccount == 0)
                {
                    if (materialsEditContentDto.ModelId != Guid.Empty && materialsEditContentDto.SendTimeId != Guid.Empty)
                    {
                        var moduleResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.ModelId).Result;
                        var sendTimeResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.SendTimeId).Result;
                        if (moduleResult == null || sendTimeResult == null)
                        {
                            storeReturnIdDto.code = 1;
                            storeReturnIdDto.Message = "字典中不存在该型号或发次请核对！";
                            return storeReturnIdDto;
                        }
                        BomDesign bomDesign = new BomDesign
                        {
                            MaterialsContentId = guid,
                            BomType = "",
                            IsUsed = 0,
                            ChangeId = Guid.Empty,
                            Status = (int)DocumentStatus.待维护,
                            Id = Guid.NewGuid(),
                            Module = moduleResult.Description,
                            SendTime = sendTimeResult.Description,
                            ModuleId = moduleResult.Id,
                            SendTimeId = sendTimeResult.Id
                        };
                        await _bomDesignrepository.InsertAsync(bomDesign);
                    }
                }
                else
                {
                    storeReturnIdDto.code = 1;
                    storeReturnIdDto.Message = "此型号、发次已添加无须重复添加！";
                    return storeReturnIdDto;
                    //throw new UserFriendlyException("此型号、发次已添加无须重复添加！");
                }
                //if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                //{
                //    var queryBomDesign = _bomDesignrepository.FirstOrDefaultAsync(t => t. == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId).Result;
                //    if (queryBomDesign!=null) {

                //        _iOperationHistoryAppService.InsertOperationLogNew(queryBomDesign.Id, BusinessTypes.设计bom, OperationTypes.设计bom添加子级, "【设计bom添加子级反向建模】-->型号：" + queryBomDesign.Module + "，发次：" + queryBomDesign.SendTime + "，" + (MaterialsEnum.MaterialProperty)materialsEditContentDto.MaterialProperty + ":" + materialsEditContentDto.MaterialNo);
                //    }
                //}
                storeReturnIdDto.MaterialCategoryId = materialsContent.MaterialCategoryId;
                storeReturnIdDto.MaterialsNodeId = materialsContent.MaterialsNodeId;
                storeReturnIdDto.MaterialsContentId = guid;
                storeReturnIdDto.MaterialTypeCode = materialsEditContentDto.MaterialTypeCode;
                storeReturnIdDto.code = 0;
                //  storeReturnIdDto.materialsContentDto = query;
                return storeReturnIdDto;
            }
            catch (Exception ex)
            {
                storeReturnIdDto.code = 1;
                storeReturnIdDto.Message = ex.Message;
                return storeReturnIdDto;
            }
        }
        /// <summary>
        /// 增加物料详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<StoreReturnIdDto> CreateErnalMaterialsContent(MaterialsEditContentDto materialsEditContentDto)
        {

            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            try
            {
                int queryCount = 0;
                Guid nodeTypeId = Guid.Empty;
                var model = materialsEditContentDto.Model == null || materialsEditContentDto.Model == "" ? "-" : materialsEditContentDto.Model.Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                materialsEditContentDto.MaterialNo = materialsEditContentDto.MaterialNo.ToUpper();
                queryCount = _materialsContentRepository.Count(t => t.MaterialNo == materialsEditContentDto.MaterialNo && t.Model == model);
                if (queryCount > 0)
                {
                    storeReturnIdDto.code = 1;
                    storeReturnIdDto.Message = "物料建模中已存在相同图号规格！无需重复添加";
                    return storeReturnIdDto;
                    //throw new UserFriendlyException("该物料已存在！");
                }
                if (materialsEditContentDto.ModelId != Guid.Empty && materialsEditContentDto.SendTimeId != Guid.Empty)
                {
                    queryCount = _materialsContentRepository.Count(t => t.ModelId == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId);
                    if (queryCount == 0)
                    {
                        if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.整装)
                        {
                            var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.整装.ToString()).Result;
                            if (materialsNode != null)
                            {
                                nodeTypeId = materialsNode.Id;
                            }
                        }
                    }
                }
                else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                {

                    if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.芯级.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                        }
                    }
                    else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.部件.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                            model = "-";
                        }
                    }
                    else if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == MaterialsEnum.MaterialProperty.组件.ToString()).Result;
                        if (materialsNode != null)
                        {
                            nodeTypeId = materialsNode.Id;
                        }
                    }
                }
                //else
                //{
                //    queryCount = _materialsContentRepository.Count(t => t.MaterialNo == materialsEditContentDto.MaterialNo && t.Model == materialsEditContentDto.Model);
                //}

                //if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.整装 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                //{
                //    materialsEditContentDto.MaterialsNodeId = Guid.Parse("a32a2fae-3938-4937-8906-0e831debbe93");
                //}
                //string typeCode = "";
                //if (materialsEditContentDto.MaterialCategoryId != Guid.Empty) 
                //{
                //    var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId).Result;
                //    typeCode = materialsNode.MaterialsTypeCode+"_"+1;
                //}

                if (materialsEditContentDto.MaterialCategoryId != Guid.Empty && materialsEditContentDto.MaterialsNodeId != Guid.Empty && materialsEditContentDto.MaterialTypeCode == null)
                {
                    Guid parenCode = Guid.Empty;
                    if (materialsEditContentDto.MaterialCategoryId == materialsEditContentDto.MaterialsNodeId)
                    {
                        var queryMaterialsDesc = _materiaDesclsRepository.GetAll().FirstOrDefaultAsync().Result;
                        if (queryMaterialsDesc != null)
                        {
                            parenCode = queryMaterialsDesc.Id;
                        }
                        var queryMaterialsNodeContent = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId && t.ParentCode == parenCode).Result;
                        if (queryMaterialsNodeContent != null)
                        {
                            materialsEditContentDto.MaterialTypeCode = queryMaterialsNodeContent.MaterialsTypeCode;
                        }
                    }
                    else
                    {

                        var queryMaterialsNodeContent = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId && t.ParentCode == materialsEditContentDto.MaterialsNodeId).Result;
                        if (queryMaterialsNodeContent != null)
                        {
                            materialsEditContentDto.MaterialTypeCode = queryMaterialsNodeContent.MaterialsTypeCode;
                        }
                    }

                }

                MaterialsContent materialsContent = new MaterialsContent()
                {
                    //物料代码
                    MaterialNo = materialsEditContentDto.MaterialNo,
                    //物料名称
                    MaterialName = materialsEditContentDto.MaterialName,
                    //规格型号
                    Model = model,
                    //类型id
                    MaterialsNodeId = nodeTypeId == Guid.Empty ? materialsEditContentDto.MaterialsNodeId : nodeTypeId,
                    //单位
                    UnitId = materialsEditContentDto.UnitId,
                    //是否使用
                    IsUsed = materialsEditContentDto.IsUsed,
                    //是否关键件
                    IsKeyPart = materialsEditContentDto.IsKeyPart,
                    //是否标准件
                    IsStandard = materialsEditContentDto.IsStandard,
                    //备注
                    Remark = materialsEditContentDto.Remark,
                    //图号
                    DrawingNo = materialsEditContentDto.DrawingNo,
                    //发次
                    // SendTime = materialsEditContentDto.SendTime,
                    //物料类别组合编码
                    MaterialTypeCode = nodeTypeId == Guid.Empty ? materialsEditContentDto.MaterialTypeCode : nodeTypeId + "_1",
                    //物料属性
                    MaterialProperty = materialsEditContentDto.MaterialProperty,
                    //物料细分类别
                    MaterialCategoryId = materialsEditContentDto.MaterialCategoryId,
                    //批次
                    Batch = materialsEditContentDto.Batch,
                    SendTime = materialsEditContentDto.SendTime,
                    ModelId = materialsEditContentDto.ModelId,
                    SendTimeId = materialsEditContentDto.SendTimeId
                };
                //add start 11/30
                //if (materialsContent.MaterialTypeCode == null)
                //{
                //    var materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialsNodeId);
                //    if (materialsContent.MaterialCategoryId == Guid.Empty)
                //    {
                //        if (materialsNode != null)
                //        {
                //            materialsContent.MaterialTypeCode = materialsContent.MaterialTypeCode + "_1";
                //        }
                //        else 
                //        {
                //            materialsContent.MaterialTypeCode = "fa568b8c-4eb5-47b1-92b1-f5aaff234de4_1";
                //        }
                //    }
                //    else
                //    {
                //        materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialCategoryId);
                //        if (materialsNode != null)
                //        {
                //            materialsContent.MaterialTypeCode = materialsContent.MaterialTypeCode + "_1";
                //        }
                //        else
                //        {
                //            materialsContent.MaterialTypeCode = "fa568b8c-4eb5-47b1-92b1-f5aaff234de4_1";
                //        }
                //    }
                //};
                //end 11/30
                var guid = await _materialsContentRepository.InsertAndGetIdAsync(materialsContent);
                _unitOfWorkManager.Current.SaveChanges();
                //_unitOfWorkManager.Current.SaveChanges();
                //var query = (from materialsContentQuery in _materialsContentRepository.GetAll().Where(t => t.MaterialProperty == 0&&t.Id ==guid)
                //            join matgerialsNode in _materialsNodeRepository.GetAll()
                //            on materialsContent.MaterialsNodeId equals matgerialsNode.Id
                //            into Joinnc
                //            from bm in Joinnc.DefaultIfEmpty()
                //            join materialsNode2 in _materialsNodeRepository.GetAll()
                //            on materialsContent.MaterialCategoryId equals materialsNode2.Id
                //            into Joinmn
                //            from mn in Joinmn.DefaultIfEmpty()
                //            join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                //               into codeData
                //            from cd in codeData.DefaultIfEmpty()
                //            join code2 in _sysCodeRepository.GetAll() on materialsContent.ModelId equals code2.Id
                //                        into codeData2
                //            from cd2 in codeData2.DefaultIfEmpty()
                //            join code3 in _sysCodeRepository.GetAll() on materialsContent.SendTimeId equals code3.Id
                //            into codeData3
                //            from cd3 in codeData3.DefaultIfEmpty()
                //            where (materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.整装) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.部件) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.组件))
                //            select new BomMainSelectParentContentListDto
                //            {
                //                Id = materialsContent.Id,
                //                MaterialTypeId = materialsContent.MaterialsNodeId,
                //                MaterialNo = materialsContent.MaterialNo,
                //                MaterialName = materialsContent.MaterialName,
                //                Model = cd2.Description,
                //                MaterialTypeName = bm.MaterialTypeName,
                //                MaterialSegmentationName = mn.MaterialTypeName,
                //                IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                //                DrawingNo = materialsContent.DrawingNo,
                //                // Unit1BomDosage = bd.Unit1BomDosage,
                //                UnitId = materialsContent.UnitId,
                //                UnitName = cd.Description,
                //                Remark = materialsContent.Remark,
                //                Attribute = materialsContent.MaterialProperty,
                //                SendTime = cd3.Description,
                //                ModelId = materialsContent.ModelId,
                //                SendTimeId = materialsContent.SendTimeId
                //            }).FirstOrDefault();

                var fccount = _bomDesignrepository.Count(t => t.ModuleId == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId);

                if (fccount == 0)
                {
                    if (materialsEditContentDto.ModelId != Guid.Empty && materialsEditContentDto.SendTimeId != Guid.Empty)
                    {
                        var moduleResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.ModelId).Result;
                        var sendTimeResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.SendTimeId).Result;
                        if (moduleResult == null || sendTimeResult == null)
                        {
                            storeReturnIdDto.code = 1;
                            storeReturnIdDto.Message = "字典中不存在该型号或发次请核对！";
                            return storeReturnIdDto;
                        }
                        BomDesign bomDesign = new BomDesign
                        {
                            MaterialsContentId = guid,
                            BomType = "",
                            IsUsed = 0,
                            ChangeId = Guid.Empty,
                            Status = (int)DocumentStatus.待维护,
                            Id = Guid.NewGuid(),
                            Module = moduleResult.Description,
                            SendTime = sendTimeResult.Description,
                            ModuleId = moduleResult.Id,
                            SendTimeId = sendTimeResult.Id
                        };
                        await _bomDesignrepository.InsertAsync(bomDesign);
                    }
                }
                else
                {
                    storeReturnIdDto.code = 1;
                    storeReturnIdDto.Message = "此型号、发次已添加无须重复添加！";
                    return storeReturnIdDto;
                    //throw new UserFriendlyException("此型号、发次已添加无须重复添加！");
                }
                //if (materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || materialsEditContentDto.MaterialProperty == (int)MaterialsEnum.MaterialProperty.芯级)
                //{
                //    var queryBomDesign = _bomDesignrepository.FirstOrDefaultAsync(t => t. == materialsEditContentDto.ModelId && t.SendTimeId == materialsEditContentDto.SendTimeId).Result;
                //    if (queryBomDesign!=null) {

                //        _iOperationHistoryAppService.InsertOperationLogNew(queryBomDesign.Id, BusinessTypes.设计bom, OperationTypes.设计bom添加子级, "【设计bom添加子级反向建模】-->型号：" + queryBomDesign.Module + "，发次：" + queryBomDesign.SendTime + "，" + (MaterialsEnum.MaterialProperty)materialsEditContentDto.MaterialProperty + ":" + materialsEditContentDto.MaterialNo);
                //    }
                //}
                storeReturnIdDto.MaterialCategoryId = materialsContent.MaterialCategoryId;
                storeReturnIdDto.MaterialsNodeId = materialsContent.MaterialsNodeId;
                storeReturnIdDto.MaterialsContentId = guid;
                storeReturnIdDto.MaterialTypeCode = materialsEditContentDto.MaterialTypeCode;
                storeReturnIdDto.code = 0;
                //  storeReturnIdDto.materialsContentDto = query;
                return storeReturnIdDto;
            }
            catch (Exception ex)
            {
                storeReturnIdDto.code = 1;
                storeReturnIdDto.Message = ex.Message;
                return storeReturnIdDto;
            }
        }
        /// 更新物料建模详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<StoreReturnIdDto> UpdateMaterialsContent(MaterialsEditContentDto materialsEditContentDto)
        {
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            try
            {
                //materialsEditContentDto.DrawingNo = materialsEditContentDto.DrawingNo.ToUpper();
                materialsEditContentDto.MaterialNo = materialsEditContentDto.MaterialNo.ToUpper();
                materialsEditContentDto.Model = materialsEditContentDto.Model.ToUpper();
                var materialsContentData = await _materialsContentRepository.FirstOrDefaultAsync(c => c.Id == materialsEditContentDto.Id);
                if (materialsContentData != null)
                {
                    string typeCode = "";
                    if (materialsEditContentDto.MaterialCategoryId != Guid.Empty)
                    {
                        var materialsNode = _materialsNodeRepository.FirstOrDefaultAsync(t => t.Id == materialsEditContentDto.MaterialCategoryId).Result;
                        typeCode = materialsNode.MaterialsTypeCode + "_" + 1;
                    }

                    materialsEditContentDto.MaterialTypeCode = typeCode;
                    var materialsEditContentNew = ObjectMapper.Map(materialsEditContentDto, materialsContentData);
                    //var list = ObjectMapper.Map<List<MaterialsContent>>(materialsEditContentDto);


                    await _materialsContentRepository.UpdateAsync(materialsEditContentNew);
                }
                else
                {
                    storeReturnIdDto.code = 1;
                    storeReturnIdDto.Message = "该物料不存在";
                    return storeReturnIdDto;
                    //throw new UserFriendlyException("该物料不存在");
                }
                storeReturnIdDto.code = 0;
                return storeReturnIdDto;
            }
            catch (Exception ex)
            {
                storeReturnIdDto.code = 1;
                storeReturnIdDto.Message = ex.Message;
                return storeReturnIdDto;
            }
        }
        /// <summary>
        /// 删除物料详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteMaterialsContent(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var materialsContentData = await _materialsContentRepository.FirstOrDefaultAsync(x => x.Id == id);

                if (materialsContentData != null)
                {
                    await _materialsContentRepository.DeleteAsync(id);
                    resultMessage.code = 0;
                    return resultMessage;
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "没有找到对应物料的详细信息";
                    return resultMessage;
                    //throw new UserFriendlyException("没有找到对应物料的详细信息");
                }
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 获取单位
        /// </summary>
        /// <returns></returns>
        public async Task<List<MaterialsOtherDto>> GetCode(Guid guid)
        {
            var queryCode = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                            join scc in _sysCodeRepository.GetAll()
                            on sc.PPtr equals scc.Id
                            where scc.Description == "单位"
                            select new MaterialsOtherDto
                            {
                                label = sc.Description,
                                value = sc.Id
                            };
            if (queryCode.Count() > 0)
            {
                return queryCode.ToList();
            }
            return new List<MaterialsOtherDto>();

        }

        /// <summary>
        /// 获取添加物料模态框的物料类型
        /// </summary>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetMaterialsType()
        {
            var queryMaterialsType = from queryMaterialstTypeData in _materialsNodeRepository.GetAll()
                                     join queryMaterialsDesc in _materiaDesclsRepository.GetAll() on queryMaterialstTypeData.ParentCode equals
                                     queryMaterialsDesc.Id
                                     select new MaterialsOtherDto
                                     {
                                         label = queryMaterialstTypeData.MaterialTypeName,
                                         value = queryMaterialstTypeData.Id
                                     };
            if (queryMaterialsType.Count() > 0)
            {
                return queryMaterialsType.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 获取添加物料模态框的物料细分类型
        /// </summary>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetSegmentationMaterialsType(string materialstTypeCode)
        {
            if (materialstTypeCode.IndexOf('_') > 0 && !string.IsNullOrEmpty(materialstTypeCode))
            {
                string[] sArray = materialstTypeCode.Split("_");
                materialstTypeCode = sArray[0];
            }

            var queryMaterialsType = from queryMaterialstTypeData in _materialsNodeRepository.GetAll().Where(t => t.MaterialsTypeCode.StartsWith(materialstTypeCode))
                                     select new MaterialsOtherDto
                                     {
                                         label = queryMaterialstTypeData.MaterialTypeName,
                                         value = queryMaterialstTypeData.Id
                                     };
            // .Union
            //(from queryMaterialstTypeData in _materialsNodeRepository.GetAll().Where(t => t.MaterialsTypeCode.StartsWith(materialstTypeCode))
            // select new MaterialsTypeDto
            // {
            //     label = queryMaterialstTypeData.MaterialTypeName,
            //     value = queryMaterialstTypeData.Id
            // });

            if (queryMaterialsType.Count() > 0)
            {
                return queryMaterialsType.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 导出Materials主页内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns> 
        public async Task<string> GetMaterialsContentToExcel(GetMaterialsContentListInput input)
        {
            List<MaterialsContentDto> materialsContents = new List<MaterialsContentDto>();
            var userData = _userRepository.GetAll().ToList();
            var query = from materialsContent in _materialsContentRepository.GetAll().
                        WhereIf(!input.MaterialTypeId.Equals(Guid.Empty), x => x.MaterialTypeCode.StartsWith(input.MaterialTypeCode))
                          .WhereIf(!input.MaterialName.IsNullOrWhiteSpace(), t => t.MaterialName.StartsWith(input.MaterialName)).WhereIf(!input.Model.IsNullOrWhiteSpace(), t => t.Model.StartsWith(input.Model))
                            //.WhereIf(!input.MaterialTypeId.Equals(Guid.Empty) && !input.MaterialCategoryId.Equals(Guid.Empty), x => x.MaterialCategoryId.Equals(input.MaterialTypeId))
                        join materialsNode in _materialsNodeRepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.StartsWith(input.MaterialTypeName)) on materialsContent.MaterialsNodeId equals materialsNode.Id
                        join materialsNodeTwo in _materialsNodeRepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeTwo.Id
                        into materialsSegmentation
                        from ms in materialsSegmentation.DefaultIfEmpty()
                        join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                        into codeData
                        from cd in codeData.DefaultIfEmpty()
                        join users in userData on materialsContent.CreatorUserId equals users.Id
                        select new MaterialsContentDto
                        {
                            Id = materialsContent.Id,
                            MaterialName = materialsContent.MaterialName,
                            MaterialNo = materialsContent.MaterialNo,
                            Model = materialsContent.Model,
                            MaterialTypeName = materialsNode.MaterialTypeName,
                            UnitId = cd ==null?Guid.Empty: cd.Id,
                            Unit = cd == null ? "": cd.Description,
                            IsUsed = Enum.Parse(typeof(MaterialsEnum.UsedIs), materialsContent.IsUsed.ToString()).ToString(),
                            IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                            IsStandard = Enum.Parse(typeof(MaterialsEnum.IsStandard), materialsContent.IsStandard.ToString()).ToString(),
                            Remark = materialsContent.Remark,
                            MaterialTypeId = materialsContent.MaterialsNodeId,
                            MaterialProperty = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialsContent.MaterialProperty.ToString()).ToString(),
                            MaterialPropertyId = materialsContent.MaterialProperty,
                            CreateUser = users.Surname + users.Name,
                            MaterialCategoryName = ms.MaterialTypeName
                        };
            if (query != null && query.Count() > 0)
            {
                return _materialsExportListExcelExporter.ExportToFile(query.OrderByDescending(t => t.CreationTime).ToList());
            }
            return null;
        }

        /// <summary>
        /// 导入物料信息
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMessage> GetExcelToMaterialsContent(Guid guid, IFormFile file)
        {
            ResultMessage result = new ResultMessage();
            if (file == null)
            {
                result.code = 1;
                result.Message = "没有找到有效文件";
                return result;
                //throw new UserFriendlyException("没有找到有效文件");
            }
            try
            {
                StringBuilder errorMsg = new StringBuilder(); // 错误信息
                List<MaterialsContent> materialsContentsList = new List<MaterialsContent>();
                // 单元格抬头
                // key：实体对象属性名称，可通过反射获取值
                // value：属性对应的中文注解
                Dictionary<string, string> cellheader = new Dictionary<string, string> {
                    { "MaterialNo", "物料代码" },
                    { "MaterialName", "物料名称" },
                    { "MaterialProperty", "属性" },
                    { "MaterialTypeName", "物料类型名称" },
                    { "MaterialCategoryName", "物料细分类别名称" },
                    { "Model", "规格型号" },
                    { "Unit", "主单位" },
                    { "IsKeyPart", "是否关键件" },
                     { "IsStandard", "是否标准件" }
                };
                // 1.2解析文件，存放到一个List集合里
                List<MaterialsContentDto> enlist = _materialsImportToTable.GetExcelList<MaterialsContentDto>(cellheader, file, out errorMsg);
                #region 校验
                #region 检测是否必填与值的有效性 
                if (enlist.Count == 0)
                {
                    result.code = 1;
                    result.Message = "文件中无值";
                    return result;
                    //throw new UserFriendlyException("文件中无值");
                }
                for (int i = 0; i < enlist.Count; i++)
                {
                    MaterialsContentDto en = enlist[i];
                    string errorMsgStr = "第" + (i + 1) + "行数据检测异常：";
                    bool isHaveNoInputValue = false; // 是否含有未输入项
                    if (string.IsNullOrEmpty(en.MaterialNo))
                    {
                        errorMsgStr += "物料代码列不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(en.MaterialProperty))
                    {
                        errorMsgStr += "物料属性不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(en.MaterialTypeName))
                    {
                        errorMsgStr += "物料类型名称不能为空；";
                        isHaveNoInputValue = true;
                    }
                    else
                    {
                        int queryMaterialType = _materialsNodeRepository.Count(t => t.MaterialTypeName == en.MaterialTypeName);
                        if (queryMaterialType == 0)
                        {
                            errorMsgStr += "物料类型名称与现有类型不符；";
                            isHaveNoInputValue = true;
                        }
                        int queryMaterialContent = _materialsContentRepository.Count(t => t.MaterialName == en.MaterialName && t.Model == en.Model);
                        if (queryMaterialContent > 0)
                        {
                            errorMsgStr += "已存在该物料；";
                            isHaveNoInputValue = true;
                        }
                    }
                    if (string.IsNullOrEmpty(en.MaterialCategoryName))
                    {
                        errorMsgStr += "物料细分类别名称不能为空；";
                        isHaveNoInputValue = true;
                    }
                    else
                    {
                        int queryMaterialCategoryCount = _materialsNodeRepository.Count(t => t.MaterialTypeName == en.MaterialCategoryName);
                        if (queryMaterialCategoryCount == 0)
                        {
                            errorMsgStr += "物料细分列别名称与现有类型不符；";
                            isHaveNoInputValue = true;
                        }
                    }
                    if (string.IsNullOrEmpty(en.Unit))
                    {
                        errorMsgStr += "物料单位列不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(en.IsKeyPart))
                    {
                        errorMsgStr += "是否关键件列不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (isHaveNoInputValue) // 若必填项有值未填
                    {
                        en.IsExcelVaildateOK = false;
                        errorMsg.AppendLine(errorMsgStr);
                    }
                }
                #endregion

                #region 2.2检测Excel中是否有重复对象

                for (int i = 0; i < enlist.Count; i++)
                {
                    MaterialsContentDto enA = enlist[i];
                    if (enA.IsExcelVaildateOK == false) // 上面验证不通过，不进行此步验证
                    {
                        continue;
                    }

                    for (int j = i + 1; j < enlist.Count; j++)
                    {
                        MaterialsContentDto enB = enlist[j];
                        // 判断必填列是否全部重复
                        if (enA.MaterialNo == enB.MaterialNo)
                        {
                            enA.IsExcelVaildateOK = false;
                            enB.IsExcelVaildateOK = false;
                            errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                        }
                        // 判断必填列是否全部重复
                        if (enA.Model == enB.Model)
                        {
                            enA.IsExcelVaildateOK = false;
                            enB.IsExcelVaildateOK = false;
                            errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                        }
                    }
                }
                #endregion
                #endregion
                #region 对数据进行持久化操作
                if (enlist.Count > 0 && errorMsg.Length == 0)
                {
                    foreach (MaterialsContentDto ms in enlist)
                    {
                        if (ms.MaterialProperty == MaterialsEnum.MaterialProperty.整装.ToString())
                        {
                            ms.MaterialPropertyId = (int)MaterialsEnum.MaterialProperty.整装;
                        }
                        else if (ms.MaterialProperty == MaterialsEnum.MaterialProperty.部件.ToString())
                        {
                            ms.MaterialPropertyId = (int)MaterialsEnum.MaterialProperty.部件;
                        }
                        else if (ms.MaterialProperty == MaterialsEnum.MaterialProperty.组件.ToString())
                        {
                            ms.MaterialPropertyId = (int)MaterialsEnum.MaterialProperty.组件;
                        }
                        else if (ms.MaterialProperty == MaterialsEnum.MaterialProperty.零件.ToString())
                        {
                            ms.MaterialPropertyId = (int)MaterialsEnum.MaterialProperty.零件;
                        }
                        var queryMaterialType = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == ms.MaterialTypeName).Result;
                        var queryMaterialCategoryType = _materialsNodeRepository.FirstOrDefaultAsync(t => t.MaterialTypeName == ms.MaterialCategoryName).Result;
                        ms.MaterialTypeId = queryMaterialType.Id;
                        ms.MaterialCategoryId = queryMaterialCategoryType.Id;
                        if (ms.IsKeyPart == "是")
                        {
                            ms.IsKeyPart = "1";
                        }
                        else
                        {
                            ms.IsKeyPart = "2";
                        }

                        if (ms.IsStandard == "是")
                        {
                            ms.IsStandard = "1";
                        }
                        else
                        {
                            ms.IsStandard = "2";
                        }
                        MaterialsContent materialsContent = new MaterialsContent()
                        {
                            MaterialName = ms.MaterialName,
                            MaterialNo = ms.MaterialNo,
                            MaterialProperty = ms.MaterialPropertyId,
                            MaterialsNodeId = ms.MaterialTypeId,
                            IsKeyPart = Convert.ToInt32(ms.IsKeyPart),
                            IsStandard = Convert.ToInt32(ms.IsStandard),
                            Model = ms.Model,
                            MaterialTypeCode = queryMaterialType.MaterialsTypeCode,
                            Remark = ms.Remark,
                            MaterialCategoryId = ms.MaterialCategoryId
                        };
                        materialsContentsList.Add(materialsContent);
                    }
                    if (materialsContentsList.Count() > 0)
                    {
                    await    _materialsContentRepository.GetDbContext().BulkInsertAsync(materialsContentsList);
                    }
                }
                #endregion
                if (errorMsg.Length > 0)
                {
                    result.code = 1;
                    result.Message = errorMsg.ToString();
                    return result;
                    //throw new UserFriendlyException(errorMsg.ToString());
                }
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
            //return "success";
        }
        /// <summary>
        /// 查出所有的物料详细信息
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<InsertDetailsDto>> GetmaterialsContentAll(GetMaterialsContetntsInProcedures input)
        {
            var queryMaterilsContent = from materilsContent in _materialsContentRepository.GetAll().WhereIf(!input.MaterialName.IsNullOrWhiteSpace(), t => t.MaterialName.Contains(input.MaterialName)).WhereIf(!input.Code.IsNullOrWhiteSpace(), t => (t.MaterialNo + " " + t.Model).Contains(input.Code)). //add 11/30
                                       Where(t => t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                       select new InsertDetailsDto
                                       { 
                                            Id = materilsContent.Id,
                                           Code = (materilsContent.MaterialNo + (materilsContent.Model == "-" ? "" : " " + materilsContent.Model)).TrimStart(),
                                           Name = materilsContent.MaterialName,
                                           Remark = materilsContent.Remark
                                       };
            if (queryMaterilsContent != null)
            {
                var queryBomContentDataList = await queryMaterilsContent.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                return new PagedResultDto<InsertDetailsDto>(queryMaterilsContent.Count(), queryBomContentDataList);
            }
            return new PagedResultDto<InsertDetailsDto>();
        }
        /// <summary>
        /// 根据型号发次查出BOM下所有物料详细信息 11/30
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<BomEditList>GetBomMaterialsContentAll(Guid moduleId, Guid sendTimeId)
        {
            var bomDesign = _bomDesignrepository.FirstOrDefault(s => s.ModuleId == moduleId && s.SendTimeId == sendTimeId);
            if (bomDesign != null)
            {
                GetBomNodeTreeListInput getBomNodeTreeListInput = new GetBomNodeTreeListInput();
                getBomNodeTreeListInput.BomId = bomDesign.Id;
                var queryMaterilsContent = GetBomTreeGridByModif(getBomNodeTreeListInput).ToList();
                if (queryMaterilsContent != null)
                {
                    return queryMaterilsContent;
                }
            }
            return new List<BomEditList>();
        }
        private List<BomEditList> GetBomTreeGridByModif(GetBomNodeTreeListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            Guid guid = Guid.NewGuid();
            List<BomEditList> querybomEditList = null;
            List<BomDetaillist> querybomdetaillists = null;
            List<BomDetaillist> bomdetailList = new List<BomDetaillist>();
            BomDetaillist bomdetaillist = new BomDetaillist();
            bomdetailList.Clear();
            var queryBomDesigns = _bomDesignrepository.GetAll().Where(t => t.Id == input.BomId);
            if (queryBomDesigns.Count() > 0)
            {
                querybomEditList = (from bomDesign in _bomDesignrepository.GetAll().Where(t => t.Id == input.BomId)
                                    join materialasContent in _materialsContentRepository.GetAll() on
                                    bomDesign.MaterialsContentId equals materialasContent.Id
                                    join matialsNode in _materialsNodeRepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                    join userParentData in userData on bomDesign.CreatorUserId equals userParentData.Id into Joinmu
                                    from mu in Joinmu.DefaultIfEmpty()
                                    select new BomEditList
                                    {
                                        data = new BomEditParentData
                                        {
                                            MaterialsContentId = bomDesign.MaterialsContentId,
                                            BomType = bomDesign.BomType,
                                            VersionNo = bomDesign.VersionNo,
                                            IsUsed = bomDesign.IsUsed,
                                            ChangeId = bomDesign.ChangeId,
                                            Status = -1,
                                            MaterialName = materialasContent.MaterialName,
                                            MaterialNo = materialasContent.MaterialNo,
                                            Id = materialasContent.Id,
                                            MaterialTypeName = matialsNode.MaterialTypeName,
                                            Model = materialasContent.Model,
                                            MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                            Remark = materialasContent.Remark,
                                            CreateUserName = mu.Surname + mu.Name,
                                            CreateTime = bomDesign.CreationTime,
                                            Btid = input.BomId

                                        }
                                    }).OrderBy(t => t.data.OrderNum).ToList();
            }
            //根据bom父节点id找出相关二级节点信息
            querybomdetaillists = (from bomdetaillistTwo in _bomDesignDetailrepository.GetAll().Where(t => t.BomDesignId == input.BomId && t.ParentId == Guid.Empty)
                                   join materialasContent in _materialsContentRepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                   join matialsNode in _materialsNodeRepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                   join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                   from mu in Joinmu.DefaultIfEmpty()
                                   select new BomDetaillist
                                   {
                                       data = new BomEditChildData
                                       {
                                           BomDesignId = bomdetaillistTwo.BomDesignId,
                                           MaterialId = bomdetaillistTwo.MaterialId,
                                           ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                           Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                           MaterialName = materialasContent.MaterialName,
                                           LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                           MaterialNo = materialasContent.MaterialNo,
                                           Id = bomdetaillistTwo.Id,
                                           LevelNum = bomdetaillistTwo.LevelNum,
                                           MaterialTypeName = matialsNode.MaterialTypeName,
                                           Model = materialasContent.Model,
                                           Remark = materialasContent.Remark,
                                           MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                           CreateUserName = mu.Surname + mu.Name,
                                           Status = -1,
                                           CreateTime = bomdetaillistTwo.CreationTime,
                                           VersionNo = bomdetaillistTwo.VersionNo,
                                           Btid = input.BomId,
                                           OrderNum = bomdetaillistTwo.OrderNum
                                       },
                                       children = new List<BomDetaillist>()
                                   }).OrderBy(t => t.data.OrderNum).ToList();
            if (querybomdetaillists != null && querybomdetaillists.Count() > 0)
            {
                foreach (BomDetaillist bomdetaillists in querybomdetaillists)
                {
                    querybomEditList.ToList()[0].children.Add(bomdetaillists);
                    //GetBomLookList(querybomEditList.ToList()[0], bomdetaillists.Id, bomdetaillists);
                    guid = bomdetaillists.data.Id;
                    bomdetaillist = bomdetaillists;
                    GetBomLookListByModif(guid, bomdetaillist, userData, Guid.Empty);
                    bomdetailList.Add(bomdetaillist);
                }
                querybomEditList.ToList()[0].children = bomdetailList;
            }

            // querybomEditListStatic = querybomEditList;
            if (querybomEditList != null)
            {
                return querybomEditList.ToList();
            }
            return new List<BomEditList>();
        }
        private BomDetaillist GetBomLookListByModif(Guid id, BomDetaillist bomdetaillist, List<User> users, Guid BTid)
        {
            //&&t.CreatorUserId == _abpSession.GetUserId()
            var queryChildBomdetaillist = (from bomChildBomDetailList in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == id)
                                           join materialasContent in _materialsContentRepository.GetAll() on bomChildBomDetailList.MaterialId equals materialasContent.Id
                                           join matialsNode in _materialsNodeRepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                           join matialsNodeChild in _materialsNodeRepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeChild.Id into mtnc
                                           from mt in mtnc.DefaultIfEmpty()
                                           join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                                into codeData
                                           from cd in codeData.DefaultIfEmpty()
                                           join userData in users on bomChildBomDetailList.CreatorUserId equals userData.Id into Joinmu
                                           from mu in Joinmu.DefaultIfEmpty()
                                           select new BomDetaillist
                                           {
                                               data = new BomEditChildData
                                               {
                                                   BomDesignId = bomChildBomDetailList.BomDesignId,
                                                   MaterialId = bomChildBomDetailList.MaterialId,
                                                   ParentMaterialId = bomChildBomDetailList.ParentMaterialId,
                                                   Unit1BomDosage = bomChildBomDetailList.Unit1BomDosage,
                                                   MaterialName = materialasContent.MaterialName,
                                                   LevelRelationship = bomChildBomDetailList.LevelRelationship,
                                                   Id = bomChildBomDetailList.Id,
                                                   ParentId = bomChildBomDetailList.ParentId,
                                                   LevelNum = bomChildBomDetailList.LevelNum,
                                                   Model = materialasContent.Model,
                                                   UnitName = cd.Code,
                                                   IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialasContent.IsKeyPart.ToString()).ToString(),
                                                   Remark = materialasContent.Remark,
                                                   MaterialTypeName = matialsNode.MaterialTypeName,
                                                   MaterialSegmentationName = mt.MaterialTypeName,
                                                   MaterialCode = bomChildBomDetailList.YearsNo == null || bomChildBomDetailList.YearsNo == "" ? (materialasContent.MaterialNo + " " + (materialasContent.Model == "-" ? "" : materialasContent.Model)).TrimEnd() : bomChildBomDetailList.YearsNo != "" || bomChildBomDetailList.YearsNo != null ? materialasContent.MaterialNo + "-" + bomChildBomDetailList.YearsNo + " " + materialasContent.Model : "",
                                                   MaterialNo = materialasContent.MaterialNo,
                                                   MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                   Status = (int)bomChildBomDetailList.Status,
                                                   CreateUserName = mu.Surname + mu.Name,
                                                   DeleStatus = (int)bomChildBomDetailList.Status == (int)DocumentStatus.已发布 || (int)bomChildBomDetailList.Status == (int)DocumentStatus.审核中 ? -1 : 0,
                                                   CreateTime = bomChildBomDetailList.CreationTime,
                                                   VersionNo = bomChildBomDetailList.VersionNo,
                                                   Btid = BTid,
                                                   OrderNum = bomChildBomDetailList.OrderNum,
                                                   YearsNo = bomChildBomDetailList.YearsNo,
                                                   WithinComponent = bomChildBomDetailList.WithinComponent
                                               },
                                               children = new List<BomDetaillist>()
                                           }).ToList().OrderBy(t => t.data.OrderNum);
            if (queryChildBomdetaillist != null && queryChildBomdetaillist.Count() > 0)
            {
                bomdetaillist.children = new List<BomDetaillist>();
                bomdetaillist.children.AddRange(queryChildBomdetaillist);

                for (int i = queryChildBomdetaillist.ToList().Count - 1; i >= 0; i--)
                {
                    if (queryChildBomdetaillist.ToList()[i].data.ParentId == bomdetaillist.data.Id)
                    {
                        //if (isbool == false)
                        //{
                        //    if (queryChildBomdetaillist.ToList()[i].data.Status == (int)DocumentStatus.已发布 || queryChildBomdetaillist.ToList()[i].data.Status == (int)DocumentStatus.审核中)
                        //    {
                        //        isbool = true;
                        //    }
                        //}
                        //if(isbool ==true)
                        //{
                        //    bomdetaillist.children[i].data.Status = 3;
                        //}
                        //TimeSpan timeSpan = queryChildBomdetaillist.ToList()[i].data.CreateTime.TimeOfDay;
                        GetBomLookListByModif(bomdetaillist.children[i].data.Id, bomdetaillist.children[i], users, BTid);
                    }
                }
            }
            return bomdetaillist;
        }
        /// <summary>
        /// 根据枚举获取枚举描述信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static string GetEnumDesc(System.Enum parm)
        {
            FieldInfo enumInfo = parm.GetType().GetField(parm.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] enumAttributes
                = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return parm.ToString();
        }



    }
}

